package com.dai.smalldemo.service.impl;

import com.dai.smalldemo.common.Result;
import com.dai.smalldemo.config.EmailConfig;
import com.dai.smalldemo.model.entity.ToEmail;
import com.dai.smalldemo.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： dkl
 * @date： 2023/12/31
 * @description：
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    private final JavaMailSender mailSender;

    private final EmailConfig emailConfig;

    private final String name ="戴康乐";

    public EmailServiceImpl(JavaMailSender mailSender, EmailConfig emailConfig) {
        this.mailSender = mailSender;
        this.emailConfig = emailConfig;
    }

    /**
     * 发送邮件
     *
     * @param toEmail
     */
    @Override
    public Result sendEmail(ToEmail toEmail) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        validateToEmail(toEmail);

        mailMessage.setFrom(emailConfig.getEmailFrom());
        mailMessage.setTo(toEmail.getTos());
        //邮件标题
        mailMessage.setSubject(toEmail.getSubject());
        //邮件内容
        mailMessage.setText(toEmail.getContent());

        try {
            mailSender.send(mailMessage);
            log.info("邮件发送成功！");
            return Result.success("邮件发送成功!");
        } catch (MailException e) {
            e.printStackTrace();
            log.info("邮件发送失败");
            return Result.success("邮件发送失败!");
        }
    }

    private static void validateToEmail(ToEmail toEmail) {
        // 判断 tos 是否为空
        Optional.ofNullable(toEmail.getTos())
                .filter(tos -> Stream.of(tos).anyMatch(Objects::nonNull))
                .orElseThrow(() -> new IllegalArgumentException("To addresses cannot be empty"));

        // 判断 subject 是否为空
        Optional.ofNullable(toEmail.getSubject())
                .filter(subject -> !subject.isEmpty())
                .orElseThrow(() -> new IllegalArgumentException("Subject cannot be empty"));

        // 判断 content 是否为空
        Optional.ofNullable(toEmail.getContent())
                .filter(content -> !content.isEmpty())
                .orElseThrow(() -> new IllegalArgumentException("Content cannot be empty"));
    }
    private static void validateHTMLToEmail(ToEmail toEmail) {
        // 判断 tos 是否为空
        Optional.ofNullable(toEmail.getTos())
                .filter(tos -> Stream.of(tos).anyMatch(Objects::nonNull))
                .orElseThrow(() -> new IllegalArgumentException("To addresses cannot be empty"));

        // 判断 subject 是否为空
        Optional.ofNullable(toEmail.getSubject())
                .filter(subject -> !subject.isEmpty())
                .orElseThrow(() -> new IllegalArgumentException("Subject cannot be empty"));


    }
    @Override
    public Result sendHtmlEmail(ToEmail toEmail) throws IOException {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        validateHTMLToEmail(toEmail);
        mailMessage.setFrom(emailConfig.getEmailFrom());
        mailMessage.setTo(toEmail.getTos());
        //邮件标题
        mailMessage.setSubject(toEmail.getSubject());
        String content = buildContent(name,"新年快乐","新年快乐，万事胜意，心想事成！");
        mailMessage.setText(content);
        try {
            mailSender.send(mailMessage);
            log.info("邮件发送成功！");
            return Result.success("邮件发送成功!");
        } catch (MailException e) {
            e.printStackTrace();
            log.info("邮件发送失败");
            return Result.success("邮件发送失败!");
        }
    }

    /**
     * 封装模板
     * @return
     * @throws IOException
     */
    public String buildContent(String name,String title,String content) throws IOException {
        Date date = new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //加载邮件html模板
        // File fileName = new File("D:\\mailtemplete.html"); // windows绝对路径
        // File fileName = new File("/opt/template/mailtemplete.html"); // linux绝对路径
        File fileName = new File("src/main/resources/templates/EmailTemplate.html"); // 相对路径
        BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.error("读取文件失败，fileName:{}", fileName, e);
        } finally {
            fileReader.close();
        }
        // 替换参数
        String htmlText = buffer.toString();
        htmlText = htmlText.replace("{name}",name);
        htmlText = htmlText.replace("{date}",sdf.format(date));
        htmlText = htmlText.replace("{title}",title);
        htmlText = htmlText.replace("{content}",content);
        /* 也可以用以下替换参数，但是我使用时报错了，若用以下替换参数的话，邮件模板（html）里面的“{title}”，“{content}”等替换成“{0}”，“{1}”等
        List<String> list = new ArrayList<>();
        list.add(name);
        list.add(sdf.format(date));
        list.add(title);
        list.add(content);
        String htmlText = MessageFormat.format(buffer.toString(), list);
        */
        return htmlText;
    }

}
